
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
import java.sql.*;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class validateUser extends HttpServlet {

	private static final long serialVersionUID = 1L;

	@Override
	public void doGet(HttpServletRequest req, HttpServletResponse res)
			throws ServletException, IOException {
		
		res.setContentType("text/html");
		PrintWriter out = res.getWriter();
		
		out.println("</body></html>");	
	}
	
	
	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	    Map<String, String> errors = new HashMap<String, String>();

	    String username = request.getParameter("user_name");
	    String password = request.getParameter("password");
	    String password2 = request.getParameter("password2");
	    String email = request.getParameter("email");
	    
		
		
	            // Open Connection Code
	            
	            Connection conn = null;
	            PreparedStatement pstmt = null;
	            ResultSet rs = null;
	            
	            try {
	                // Registering Postgresql JDBC driver with the DriverManager
	                try {
						Class.forName("org.postgresql.Driver");
					} catch (ClassNotFoundException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}

	                // Open a connection to the database using DriverManager
	                conn = DriverManager.getConnection(
	                    "jdbc:postgresql://localhost/phase2db?" +
	                    "user=postgres&password=password");
	                
	                
	                
	                //-------- SELECT Statement Code --------
	                
	                    // Create the statement
	                    Statement statement = conn.createStatement();

	                	String query = "SELECT * FROM users";
	                	rs = statement.executeQuery(query);
	                	
	                	while (rs.next())
	                	{
	                		
	                		// if the suggested username is already taken and it does not match the email
	                		if (username.equals(rs.getString("user_name")) && !email.equals(rs.getString("email")))  {
	                			errors.put("user_name", "Sorry, this username is already taken. Choose another user name.");
	                		}

	                		// if the user is already registered (i.e. his email is already in the database)
	                		// but he enters a different username
	                		if (email.equals(rs.getString("email")) && !username.equals(rs.getString("user_name")))  {
	                			errors.put("email", "This email is already registered.  If this is your email, you may proceed to submit an application by logging in with your account.");
	                		}
	                		
	                		// if the username and email are in the database (from the same account), but the suggested pw is incorrect
	                		if (username.equals(rs.getString("user_name")) && email.equals(rs.getString("email")) && !password.equals(rs.getString("password")))  {
	                			errors.put("email", "You are already registered, you may proceed to submit an application by logging in.");
	                		}
	                		
	                	}
        
		

	                	// if the user provides an empty password
	                	if (password.equals("") && errors.isEmpty())  {
	                		errors.put("password", "A password is required.");
	                	}

	                	// if the password and the retyped password are not identical
	                	if (!password.equals("") && !password.equals(password2) && errors.isEmpty())  {
	                		errors.put("password2", "The retyped password is not identical.");
	                	}
	    



	    
	    //-- -------- Close Connection Code -------- --
            // Close the ResultSet
            rs.close();

            // Close the Statement
            statement.close();

            // Close the Connection
            conn.close();
            
            
            
            if (errors.isEmpty()) {
            	// No errors, redirect to Registration Confirmation page.
            	request.setAttribute("user_name", username);
            	request.setAttribute("password", password);
            	request.setAttribute("email", email);
            	request.getRequestDispatcher("registrationConfirmation.jsp").forward(request, response);
            	// response.sendRedirect("registrationConfirmation.jsp");
            }
            else {
            	// Put errors in request scope and forward back to JSP.
            	request.setAttribute("errors", errors);
            	request.getRequestDispatcher("applicantRegistration.jsp").forward(request, response);
            }
	   }
	            
	            
	    catch (SQLException e) {
            // Wrap the SQL exception in a runtime exception to propagate
            // it upwards
            throw new RuntimeException(e);
        }
	            
        finally {
            // Release resources in a finally block in reverse-order of
            // their creation

            if (rs != null) {
                try {
                    rs.close();
                } catch (SQLException e) { } // Ignore
                rs = null;
            }
            if (pstmt != null) {
                try {
                    pstmt.close();
                } catch (SQLException e) { } // Ignore
                pstmt = null;
            }
            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException e) { } // Ignore
                conn = null;
            }
        }
        
        
	}
}
	
